/*
 * Copyright (c) 2022. China Mobile (SuZhou) Software Technology Co.,Ltd. All rights reserved.
 * Lakehouse is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *          http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 */

package com.chinamobile.cmss.lakehouse.core.config;

import com.chinamobile.cmss.lakehouse.common.exception.BaseException;

import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.io.Writer;
import java.util.Enumeration;
import java.util.Properties;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;

public class SimpleHadoopConfiguration {

    private Properties properties = new Properties();

    public void set(String key, String value) {
        properties.setProperty(key, value);
    }

    public String get(String key) {
        return properties.getProperty(key);
    }

    public void loadResource(InputStream resouce) {
        try {
            DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
            docBuilderFactory.setIgnoringComments(true);
            docBuilderFactory.setNamespaceAware(true);

            DocumentBuilder documentBuilder = docBuilderFactory.newDocumentBuilder();

            Document doc = documentBuilder.parse(resouce);
            Element root = doc.getDocumentElement();
            NodeList props = root.getChildNodes();

            for (int i = 0; i < props.getLength(); i++) {

                Node propNode = props.item(i);

                if (propNode instanceof Element) {
                    Element prop = (Element) propNode;
                    NodeList fields = prop.getChildNodes();
                    String attr = null;
                    String value = null;

                    for (int j = 0; j < fields.getLength(); ++j) {
                        Node fieldNode = fields.item(j);
                        if (fieldNode instanceof Element) {
                            Element field = (Element) fieldNode;
                            if ("name".equals(field.getTagName()) && field.hasChildNodes()) {
                                attr = ((Text) field.getFirstChild()).getData();
                            }

                            if ("value".equals(field.getTagName()) && field.hasChildNodes()) {
                                value = ((Text) field.getFirstChild()).getData();
                            }
                        }
                    }
                    if (attr != null && value != null) {
                        properties.put(attr.trim(), value.trim());
                    }
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }

    public String configContent() {

        try {
            StringWriter writer = new StringWriter();
            writeData(writer);
            writer.close();

            return writer.toString();
        } catch (IOException e) {
            throw new BaseException(e);
        }

    }

    public void writeData(Writer out) {
        try {
            Document doc = this.asXmlDocument();
            DOMSource source = new DOMSource(doc);
            StreamResult result = new StreamResult(out);
            TransformerFactory transFactory = TransformerFactory.newInstance();
            Transformer transformer = transFactory.newTransformer();
            transformer.transform(source, result);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private synchronized Document asXmlDocument() throws Exception {

        Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();

        Element conf = doc.createElement("configuration");
        doc.appendChild(conf);
        conf.appendChild(doc.createTextNode("\n"));
        for (Enumeration<Object> e = properties.keys(); e.hasMoreElements(); ) {
            String name = (String) e.nextElement();
            Object object = properties.get(name);
            String value = null;
            if (object instanceof String) {
                value = (String) object;
            } else {
                continue;
            }
            Element propNode = doc.createElement("property");
            conf.appendChild(propNode);

            Element nameNode = doc.createElement("name");
            nameNode.appendChild(doc.createTextNode(name));
            propNode.appendChild(nameNode);

            Element valueNode = doc.createElement("value");
            valueNode.appendChild(doc.createTextNode(value));
            propNode.appendChild(valueNode);

            conf.appendChild(doc.createTextNode("\n"));
        }

        return doc;
    }

}